//
//  MJTNetworkTools.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/12.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit
import AFNetworking
//定义请求枚举,默认0
enum RequestType: Int {
    case GET
    case POST
}
// 网络请求工具类
class MJTNetworkTools: AFHTTPSessionManager {
    //单例全局访问点
    static let sharedTools: MJTNetworkTools = {
        let tools = MJTNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    //  封装上传请求
    func requestUpload(url: String, params: AnyObject?, picName: String, imageData: NSData, callBack: (response: AnyObject?, error: NSError?)->()) {

        self.POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in

            //octet-stream 通用的资源类型 filename随便传服务端一般不会用，服务端自己产生唯一的图片名字
            formData.appendPartWithFileData(imageData, name: picName, fileName: "test", mimeType: "octet-stream")

            }, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)

            }) { (_, error) -> Void in
                callBack(response: nil, error: error)
        }

    }
    //封装get/post请求
    func request(type: RequestType, url: String,params: AnyObject?,callBack:(response: AnyObject?, error: NSError?)->()) {
        if type == .GET {
            GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    print(error)
                callBack(response: nil, error: error)
            })
        } else {
            POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                callBack(response: nil, error: error)
            })
        }

    }
}


//记载微博数据
extension MJTNetworkTools {

    func upload(accesstoken: String ,status: String, image: UIImage, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  准备url
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //  准备参数
        let params = [
            "access_token": accesstoken,
            "status": status
        ]


        let imageData = UIImageJPEGRepresentation(image, 0.5)!

        requestUpload(url, params: params, picName: "pic", imageData: imageData, callBack: callBack)

        //        self.POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
        //
        //            formData.appendPartWithFileData(imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
        //
        //            }, progress: nil, success: { (_, response) -> Void in
        //                callBack(response: response, error: nil)
        //
        //            }) { (_, error) -> Void in
        //                callBack(response: nil, error: error)
        //        }
        
        
    }

    //加载微博数据
    func loadStatus(maxId: Int64 = 0, sinceId: Int64 = 0, callBack:(response: AnyObject?,error: NSError?)->()) {
                //准备接口地址
                let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
                //准备参数
                let params = [
                    "access_token": MJTUserAccountViewModel.shareUserAccount.accessToken!,
                    "max_id": "\(maxId)",
                    "since_id": "\(sinceId)"
                ]
                //print(url + "?access_token=" + MJTUserAccountViewModel.shareUserAccount.accessToken!)
        request(.GET, url: url, params: params, callBack: callBack)
    }
    /**
     发送带文字微博

     - parameter accesstoken: 访问令牌
     - parameter status:      微博内容
     - parameter callBack:    网络请求回调
     */
    func update(accesstoken: String ,status: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  准备接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        //  准备参数
        let params = [
            "access_token": accesstoken,
            "status": status
        ]

        //  请求网络接口
        request(.POST, url: url, params: params, callBack: callBack)

    }

}



//OAuth 登录相关接口
extension MJTNetworkTools {
    //通过授权码获取accesstoken
    func requestAccesstoken(code: String,callBack:(response: AnyObject?,error: NSError?)->()){

        // 准备接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //  准备参数
        let params = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Url
        ]

    request(.POST, url: url, params: params, callBack: callBack)
    }

    func requestUserInfo(userAccount: MJTUserAccount,callBack:(response: AnyObject?,error: NSError?)->()) {
        let url = "https://api.weibo.com/2/users/show.json"
        //准备请求参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        //拼接地址
       // let urlStr = url + "?access_token=\(userAccount.access_token!)&uid=\(userAccount.uid)"
//        print(urlStr)
        request(.GET, url: url, params: params, callBack: callBack)
    }

}